// @ts-nocheck
import Ability from '@ohos.app.ability.UIAbility'
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { GlobalHolder, GlobalKey } from '../Application/GlobalHolder';

const permissions: Array<Permissions> = ['ohos.permission.GET_INSTALLED_BUNDLE_LIST'];

export default class MainAbility extends Ability {
    onCreate(want, launchParam) {
        console.log("[Demo] MainAbility onCreate")
        globalThis.abilityWant = want;
        GlobalHolder.getInstance().setObject<UIAbilityContext>(GlobalKey.edmContext, this.context);
        globalThis.callbackMessage = ""
    }

    onDestroy() {
        console.log("[Demo] MainAbility onDestroy")
    }

    onWindowStageCreate(windowStage) {
        // Main window is created, set main page for this ability
        console.log("[Demo] MainAbility onWindowStageCreate")

        windowStage.loadContent("pages/index", (err, data) => {
            if (err.code) {
                console.error('Failed to load the content. Cause:' + JSON.stringify(err));
                return;
            }
            console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
        });
        let context = this.context;
        let atManager = abilityAccessCtrl.createAtManager();
        // requestPermissionsFromUser���ж�Ȩ�޵���Ȩ״̬�������Ƿ��𵯴�

        atManager.requestPermissionsFromUser(context, permissions).then((data) => {
            let grantStatus: Array<number> = data.authResults;
            let length: number = grantStatus.length;
            for (let i = 0; i < length; i++) {
                if (grantStatus[i] === 0) {
                    // �û���Ȩ�����Լ�������Ŀ�����
                } else {
                    // �û��ܾ���Ȩ����ʾ�û�������Ȩ���ܷ��ʵ�ǰҳ��Ĺ��ܣ��������û���ϵͳ�����д���Ӧ��Ȩ��
                    return;
                }
            }
            // ��Ȩ�ɹ�
        }).catch((err) => {
            console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);

            // ...
        })
    }

    onWindowStageDestroy() {
        // Main window is destroyed, release UI related resources
        console.log("[Demo] MainAbility onWindowStageDestroy")
    }

    onForeground() {
        // Ability has brought to foreground
        console.log("[Demo] MainAbility onForeground")
    }

    onBackground() {
        // Ability has back to background
        console.log("[Demo] MainAbility onBackground")
    }
};
